<?php

class OptionsController extends Controller
{
	public $layout='menu';
	public function filters()
	{
		return array(
			'accessControl', // perform access control for CRUD operations
		);
	}

	public function accessRules()
	{
		return array(
			
		);
	}

	public function actionView($id)
	{
		if (!Yii::app()->user->isGuest)
	{
		$this->render('view',array(
			'model'=>$this->loadModel($id),
		));
	}
	else
	 $this->redirect(Yii::app()->createUrl('/admin/login'));
	}
	
	public function actionCreate()
	{
		if (!Yii::app()->user->isGuest)
	{
		$model= new Options();

		if(isset($_POST['Options']))
			{
			$title=Options::model()->find('question_id=? and name=?',array($_POST['Options']['question_id'],$_POST['Options']['name']));
			if($title)
			{
				Yii::app()->user->setFlash('success', "option name is already present for this question please give another name");
			}
			else{
			$name=Options::model()->findAll('question_id=?',array($_POST['Options']['question_id']));
			$n=count($name);
					if($n==4)
					{	
					Yii::app()->user->setFlash('success', "maximum 4 options are accepted for single question");
					}
					else
					{
						$option=Options::model()->find('question_id=? and correct_option=?',array($_POST['Options']['question_id'],'yes'));
						
						if($option)
						{
						$model->attributes=$_POST['Options'];
						$model->correct_option='no';
						if($model->save())
						{
						Yii::app()->user->setFlash('success', "this question have already correct answer,your option saved sucessfully with default status as no");
						$this->redirect(Yii::app()->createUrl('/admin/options/admin'));
						}
						}
						
						else
						{
							$opt=Options::model()->findAll('question_id=? and correct_option=?',array($_POST['Options']['question_id'],'no'));
							$op=count($opt);
							if($op==3)
							{
							$model->attributes=$_POST['Options'];
							$model->correct_option='yes';
							if($model->save())
							Yii::app()->user->setFlash('success', "this question have already 3 uncorrect answer,your option saved sucessfully with default status as yes");	
							$this->redirect(Yii::app()->createUrl('/admin/options/admin'));
							}
							else 
							{
						$model->attributes=$_POST['Options'];
						if($model->save())
						Yii::app()->user->setFlash('success', "option successfully get created");
						$this->redirect(Yii::app()->createUrl('/admin/options/admin'));
							}
						}
					}	
				
	}
	}
	}
	else
	 $this->redirect(Yii::app()->createUrl('/admin/login'));
	
	$this->render('create',array(
			'model'=>$model,
		));
		
	
	
	}
	
	public function actionUpdate($id)
	{
		if (!Yii::app()->user->isGuest)
	{
		$model=$this->loadModel($id);

		if(isset($_POST['Options']))
		{
			$model->attributes=$_POST['Options'];
			if($model->save())
				$this->redirect(array('view','id'=>$model->id));
		}

		$this->render('update',array(
			'model'=>$model,
		));
	}
	else
	 $this->redirect(Yii::app()->createUrl('/admin/login'));
	}
	
	public function actionDelete($id)
	{
		if (!Yii::app()->user->isGuest)
	{
		if(Yii::app()->request->isPostRequest)
		{
			// we only allow deletion via POST request
			$this->loadModel($id)->delete();

			// if AJAX request (triggered by deletion via admin grid view), we should not redirect the browser
			if(!isset($_GET['ajax']))
				$this->redirect(isset($_POST['returnUrl']) ? $_POST['returnUrl'] : array('admin'));
		
		else
			throw new CHttpException(400,'Invalid request. Please do not repeat this request again.');
	}
	}
	else
	 $this->redirect(Yii::app()->createUrl('/admin/login'));
	}
	/**
	 * Lists all models.
	 */
	public function actionIndex()
	{
		if (!Yii::app()->user->isGuest)
	{
		$dataProvider=new CActiveDataProvider('Options');
		$this->render('index',array(
			'dataProvider'=>$dataProvider,
		));
	}
	else
	 $this->redirect(Yii::app()->createUrl('/admin/login'));
	}
	/**
	 * Manages all models.
	 */
	public function actionAdmin()
	{
		if (!Yii::app()->user->isGuest)
	{
		$model=new Options('search');
		$model->unsetAttributes();  // clear any default values
		if(isset($_GET['Options']))
			$model->attributes=$_GET['Options'];

		$this->render('admin',array(
			'model'=>$model,
		));
	}
	else
	 $this->redirect(Yii::app()->createUrl('/admin/login'));
	}
	
	
	public function actionRemove()
	        {
				$id=$_GET['id']; 
				$model=$this->loadModel($id);
				
					$model->delete();
					Yii::app()->user->setFlash('success','You have successfully deleted!');
				Yii::app()->end();
	        }
	        
	        
		public function actionBatchUpdate()
		{
			$new_model=null;
			$model=Options::model()->findAllBySql('select * from options where question_id=:x ',array(':x'=>$_GET['id']));
		    $id=$_GET['id'];
        
		   if(isset($_GET['addnew']))
		   {
          $model[]=new Options();
       		}
      		 if(!empty($model))
		  	 {
		   		if(sizeof($model)<4)
		   		{
		   			$objsize=4-sizeof($model);
		   			for ($i=0;$i<$objsize;$i++)
		   			$model[]=new Options();
		   		}
		  	 }
		 	  else
		  		 {
         			for ($i=0;$i<4;$i++)
		   			$model[]=new Options();
      			 }
  		    if(isset($_POST['Options']))
		    {
		    	$valid=true;
		        foreach($model as $i=>$item)
		        {
		            if(isset($_POST['Options'][$i]))
		            {
		                $item->attributes=$_POST['Options'][$i];
		               $item->question_id=$id;
		            }
		              
		            	$valid=$item->validate();
		            	
		           if($valid){
		    			
			        	
			        	if($item->correct_option)
			        	{
			        		$item->correct_option="yes";
			        	}
			        	else
			        	{
			        		$item->correct_option="no";
			        	}
			          $item->save();
			          
		        	
		        } 
		        Yii::app()->user->setFlash('success','Your options successfully enterd!');    	
		        }
		        //$this->redirect(Yii::app()->createUrl('admin/questions/admin/id/'.$item->quiz_id));

		    }

		    	$this->render('batchUpdate',array('items'=>$model,'id'=>$id));

		}
	
	public function loadModel($id)
	{
		$model=Options::model()->findByPk($id);
		if($model===null)
			throw new CHttpException(404,'The requested page does not exist.');
		return $model;
	}
	
	/**
	 * Performs the AJAX validation.
	 * @param CModel the model to be validated
	 */
	protected function performAjaxValidation($model)
	{
		if(isset($_POST['ajax']) && $_POST['ajax']==='options-form')
		{
			echo CActiveForm::validate($model);
			Yii::app()->end();
		}
	}
}
